<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>10计算和方法的 区别</title>
  </head>
  <style>
    td {
      width: 100px;
      text-align: center;
    }
    h3{
      position: relative;
    }
    span{
      position: absolute;
      margin-top: -10px;
    }
  </style>
  <body>
    <!-- 基于现有的数据，计算出来的属性。依赖的数据变化，自动重新计算 -->
    <div id="app">
      <h3>小黑的礼物清单  购物车<span> {{ totalCountFn() }}</span></h3> 
      <h3>小黑的礼物清单  购物车<span> {{ totalCountFn() }}</span></h3> 
      <h3>小黑的礼物清单  购物车<span> {{ totalCountFn() }}</span></h3> 
      <table border="1">
        <tr>
          <th>名字</td>
          <th>数量</td>
        </tr>
        <tr v-for="item in list" :key="item.id">
          <td>{{item.name}}</td>
          <td>{{item.num}}个</td>
        </tr>
      </table>
      <p>礼物总数：{{ totalCount }} 个</p>
    </div>

    <script src="../js/vue.js"></script>
    <script>
      var app = new Vue({
        el: "#app",
        data: {
          list: [
            { id: 1, name: "篮球", num: 1 },
            { id: 2, name: "玩具", num: 2 },
            { id: 3, name: "铅笔", num: 3 },
          ],
        },
        methods: {
          totalCountFn(){
            console.log('计算属性执行了');
            return this.list.reduce((pre,cur)=>{
              return pre+cur.num
            },0);
          }
        },
        computed:{
          totalCount(){
            console.log('计算属性执行了');
            return this.list.reduce((pre,cur)=>{
              return pre+cur.num
            },0);
          }
        }
      });
    </script>
  </body>
</html>
